const getCurrentTab = async () => {
    const queryOptions = { active: true, lastFocusedWindow: true };
    // const queryOptions = { lastFocusedWindow: true };
    // const [tab] = await chrome.tabs.query({currentWindow: true, active: true});
    const [tab] = await chrome.tabs.query(queryOptions);
    console.log(tab);
    return tab;
}

const executeInCurrentTab = async (opts) => {
    const tab = await getCurrentTab();
    if (!tab) {
        throw new Error("getCurrentTab return undefined or null!");
    }
    return executeInTab(tab.id, opts);
}

const executeInTab = async (tabId, { file, func, args }) => {
    const executions = await chrome.scripting.executeScript({
        target: { tabId, allFrames: true },
        ...(file && { files: [file] }),
        func,
        args,
    });

    const validExecutions = executions.filter(item => {
        return item.result !== undefined && item.result !== null;
    });
    if (validExecutions.length == 1) {
        return validExecutions[0].result;
    }

    // If there are many frames, concatenate the results
    return validExecutions.flatMap((execution) => execution.result);
}

const wrapResponse = (promise, sendResponse) => {
    promise.then((response) => sendResponse({
        success: true,
        response,
    })).catch((error) => sendResponse({
        success: false,
        error: error.message,
    }));
}

export { executeInCurrentTab, executeInTab, wrapResponse };
